const { sequelize } = require('../config/database');
const User = require('./user.model');
const UserAddress = require('./userAddress.model');
const Banner = require('./banner.model');
const Category = require('./category.model');
const Goods = require('./goods.model');
const GoodImage = require('./goodImages.model');
const Cart = require('./cart.model');
const Order = require('./order.model');
const OrderItem = require('./order-item.model');

// 定义模型关联关系

// 分类和商品的一对多关系
Category.hasMany(Goods, {
  foreignKey: 'categoryId',
  as: 'goods'
});

Goods.belongsTo(Category, {
  foreignKey: 'categoryId',
  as: 'category'
});

// 商品和图片的一对多关系
Goods.hasMany(GoodImage, {
  foreignKey: 'goodsId',
  as: 'images'
});

GoodImage.belongsTo(Goods, {
  foreignKey: 'goodsId',
  as: 'goods'
});

// 用户和购物车的一对多关系
User.hasMany(Cart, {
  foreignKey: 'userId',
  as: 'carts'
});

Cart.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

// 商品和购物车的一对多关系
Goods.hasMany(Cart, {
  foreignKey: 'goodsId',
  as: 'carts'
});

Cart.belongsTo(Goods, {
  foreignKey: 'goodsId',
  as: 'goods'
});

// 用户和订单的一对多关系
User.hasMany(Order, {
  foreignKey: 'userId',
  as: 'orders'
});

Order.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

// 订单和订单明细的一对多关系
Order.hasMany(OrderItem, {
  foreignKey: 'orderId',
  as: 'orderItems'
});

OrderItem.belongsTo(Order, {
  foreignKey: 'orderId',
  as: 'order'
});

// 商品和订单明细的一对多关系
Goods.hasMany(OrderItem, {
  foreignKey: 'goodsId',
  as: 'orderItems'
});

OrderItem.belongsTo(Goods, {
  foreignKey: 'goodsId',
  as: 'goods'
});

// 导出模型
module.exports = { sequelize, User, UserAddress, Banner, Category, Goods, GoodImage, Cart, Order, OrderItem };